package com.wms.minio;

import io.minio.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import io.minio.BucketExistsArgs;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

@Service
public class MinioServiceImpl implements MinioService{
    @Autowired
    private MinioClient minioClient;
    @Autowired
    private MinioPojo minio;


    //上传
    @Override
    public String upload(String bucketName, MultipartFile file) {
        try {
            boolean exists =minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
            //如果桶不存在，创建桶
            if (!exists) {
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
            }
            //获取时间
            String dateTime =
                    LocalDateTime.now().format(DateTimeFormatter
                            .ofPattern("yyyy-MM-dd"));
            //UUID
            String uuid =UUID.randomUUID().toString();
            //获取文件名
            String originalFilename =
                    file.getOriginalFilename();
            String extension
                    =originalFilename.substring(originalFilename
                    .lastIndexOf("."));
            String newFileName = uuid +
                    extension;
            String fileName = dateTime + "/" +
                    newFileName;

            minioClient.putObject(PutObjectArgs.builder()
                    .bucket(bucketName)
                    .object(fileName)
                    .stream(file.getInputStream(),
                            file.getSize(), -1)
                    .contentType(file.getContentType())
                    .build());
            String url = minio.getUrl() + "/" +
                    bucketName + "/" + fileName;
            return url;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("文件上传失败");
        }

    }


    //下载
    @Override
    public ResponseEntity<InputStreamResource> download(String url) throws Exception {
        String objectUrl =url.split(minio.getBucketName() + "/")[1];
        InputStream inputStream =
                minioClient.getObject(
                        GetObjectArgs.builder()
                                .bucket(minio.getBucketName())
                                .object(objectUrl)
                                .build()
                );
        return ResponseEntity.ok()

                .contentType(MediaType.APPLICATION_OCTET_STREAM)

                .header(HttpHeaders.CONTENT_DISPOSITION,
                        "attachment; filename=\"" + url + "\"")
                .body(new
                        InputStreamResource(inputStream));
    }

    //删除
    @Override
    public String delete(String url) {
        String objectUrl =
                url.split(minio.getBucketName() + "/")[1];
        try {
            minioClient.removeObject(RemoveObjectArgs.builder()
                            .bucket(minio.getBucketName())
                            .object(objectUrl)
                            .build());
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("文件删除失败");
        }
        return "文件删除成功";
    }
}
